import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// router
import { createWebHashHistory, createRouter } from 'vue-router'
import { dynamicRoutes, staticRoutes, notFoundAndNoPower } from './route' // 展示在菜单中的路由
// store
import store from "@/stores"
import routesListPiniaStore from '@/stores/modules/routesList';
//
import { getToken } from "@/utils/token"
import { initFrontEndControlRoutes } from '@/router/frontEnd';
import { globalLoading } from '@/utils/loading';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...notFoundAndNoPower, ...staticRoutes],
});

globalLoading.start()

// 路由加载前
router.beforeEach(async (to, from, next) => {
    NProgress.configure({ showSpinner: false })
    if (to.meta.title) NProgress.start()
    const token = getToken()
    if (to.path === '/login' && !token) {
        next();
        NProgress.done()
    } else {
        if (!token) {
            next(`/login?redirect=${to.path}`)
            NProgress.done();
        } else if (token && to.path === '/login') {
            next('/components/previewImage')
            NProgress.done()
        } else {
            const routesListStore = routesListPiniaStore(store)
            const { routesList } = storeToRefs(routesListStore)
            if (routesList.value.length === 0) {
                await initFrontEndControlRoutes();
                next({ path: to.path, query: to.query });
            } else {
                next()
            }
        }
    }
})

router.afterEach(() => {
    globalLoading.done()
    NProgress.done();
})


export default router;
